package com.seele.tigerwallet.ui.views;

import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter.RequestLoadMoreListener;
import com.seele.tigerwallet.R;
import com.seele.tigerwallet.api.APIException;
import com.seele.tigerwallet.api.APIListCallBack;
import com.seele.tigerwallet.api.APIModule;
import com.seele.tigerwallet.model.AssetsModel;
import com.seele.tigerwallet.model.MarketModel;
import com.seele.tigerwallet.ui.adapter.AddMoreAdapter;
import com.seele.tigerwallet.ui.callback.BaseListener;
import com.seele.tigerwallet.ui.callback.OnSelectListener;
import com.seele.tigerwallet.ui.utils.DividerItemDecoration;
import com.seele.tigerwallet.ui.utils.GsonUtil;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import retrofit2.Call;

import static com.seele.tigerwallet.ui.adapter.AddMoreAdapter.*;

public class AddMoreRecyclerView extends RecyclerView implements RequestLoadMoreListener, OnSwitchViewClickListener {

    private AddMoreAdapter mAddMoreAdapter;
    private List<MarketModel> mBundleList;//传值
    private int num = 50;
    private List<Integer> list = new ArrayList<>();

    private Map<Integer, MarketModel> modelMap = new ConcurrentHashMap<>();

    private OnSelectListener onSelectListener;

    private List<MarketModel> mMarketModelList;


    public void setListener(BaseListener listener) {
        if (listener instanceof OnSelectListener) {
            this.onSelectListener = (OnSelectListener) listener;
        }

    }


    public AddMoreRecyclerView(Context context) {
        this(context, null);
    }

    public AddMoreRecyclerView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public AddMoreRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initView(context);
    }


    /**
     * @param context
     */
    private void initView(Context context) {
        if (null == context) {
            return;
        }

        setLayoutManager(new LinearLayoutManager(context));

//        addItemDecoration(new DividerItemDecoration(context, LinearLayoutManager.HORIZONTAL,
//                (int) getResources().getDimension(R.dimen.dp_1), getResources().getColor(R.color.color_DEDEDE))); //设置item的分割线
        if (null == mAddMoreAdapter) {
            mAddMoreAdapter = new AddMoreAdapter(R.layout.item_add_more);
        }
        mAddMoreAdapter.setOnSwitchViewClickListener(this);
//        mAddMoreAdapter.setOnLoadMoreListener(this, this);
//        mAddMoreAdapter.setEnableLoadMore(true);
        setAdapter(mAddMoreAdapter);

        mAddMoreAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                MarketModel item = null;
                if (null != mAddMoreAdapter) {
                    item = mAddMoreAdapter.getData().get(position);
                }
                switch (view.getId()) {
                    case R.id.check_ll:
                        onSelect(item);
                        break;
                }
            }
        });

    }


    /**
     * 选择移除行情处理
     *
     * @param item
     */
    private void onSelect(MarketModel item) {
        if (null == item) {
            return;
        }
        boolean isOpen = item.isOpen;
        if (isOpen) {
            item.isOpen = false;
        } else {
            item.isOpen = true;
        }
        mAddMoreAdapter.notifyDataSetChanged();

        if (null != mBundleList && mBundleList.size() > 0) {
            for (MarketModel marketModel : mBundleList) {
                list.add(marketModel.id);
            }
            if (item.isOpen) {
                if (!list.contains(item.id)) {
                    mBundleList.add(item);
                }
            } else {
                if (list.contains(item.id)) {
                    for (int i = mBundleList.size() - 1; i >= 0; i--) {
                        if (mBundleList.get(i).id == item.id) {
                            mBundleList.remove(i);
                        }
                    }
                }
            }
        } else {
            mBundleList = new ArrayList<>();
            mBundleList.add(item);

        }


        if (null != onSelectListener) {
            if (null != mBundleList) {
                onSelectListener.onSelect(mBundleList);
            }
        }
    }


    /**
     * 设置
     */
    public void setBundleList(List<MarketModel> bundleList, boolean isLoad) {
        this.mBundleList = bundleList;

        if (null == mBundleList) {
            mBundleList = new ArrayList<>();
        }

        if (null != modelMap) {
            modelMap.clear();
        }
        for (MarketModel marketModel : bundleList) {
            addModel(marketModel);
        }

        if (isLoad) {
            if (null != mMarketModelList && mMarketModelList.size() > 0) {
                handleData(mMarketModelList, true);
            } else {
                //            initData(0, true);
                initDataForRank(0, true);
            }

        } else {

        }
    }

    private void addModel(MarketModel marketModel) {
        if (null != marketModel) {
            if (!modelMap.containsKey(marketModel.id)) {
                modelMap.put(marketModel.id, marketModel);
            }
        }
    }


    @Override
    public void onLoadMoreRequested() {
        if (null != mAddMoreAdapter) {
            List<MarketModel> assetsModels = mAddMoreAdapter.getData();
            int size = assetsModels == null ? 0 : assetsModels.size();
            if (size > 0) {
                int rank = assetsModels.get(size - 1).rank + 1;
                initDataForRank(rank, false);
            }
        }

    }


    private void initDataForRank(int rank, final boolean isRefresh) {
        APIModule
                .getApi()
                .quotationRankLis(rank, num)
                .enqueue(new APIListCallBack<MarketModel>() {
                    @Override
                    protected void onResponse(List<MarketModel> response) {
                        try {
                            mMarketModelList = response;
                            handleData(response, isRefresh);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }


                    @Override
                    protected void onResponseError(APIException e) {
                        if (!isRefresh) {
                            mAddMoreAdapter.loadMoreFail();
                        }
                    }

                    @Override
                    protected void onFailureError(Call<String> call, Throwable t) {
                        if (!isRefresh) {
                            mAddMoreAdapter.loadMoreFail();
                        }

                    }


                });

    }

    /**
     * 获取网络数据
     *
     * @param id
     * @param isRefresh
     */
    private void initData(int id, final boolean isRefresh) {

        APIModule.
                getApi().
                quotationList(id, num).
                enqueue(new APIListCallBack<MarketModel>() {
                    @Override
                    protected void onResponseError(APIException e) {

                    }

                    @Override
                    protected void onFailureError(Call<String> call, Throwable t) {

                    }

                    @Override
                    protected void onResponse(List<MarketModel> response) {

                        try {
                            handleData(response, isRefresh);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }


                    }
                });

    }

    @Override
    public void onSwitchViewClick(int position, MarketModel item) {
        if (null != mAddMoreAdapter) {
            mAddMoreAdapter.getData().get(position).isOpen = item.isOpen;
        }
        if (null == mBundleList) {
            mBundleList = new ArrayList<>();
        }
        clear();
        for (MarketModel marketModel : mBundleList) {
            list.add(marketModel.id);
        }
        if (item.isOpen) {
            if (!list.contains(item.id)) {
                mBundleList.add(item);
            }
        } else {
            if (list.contains(item.id)) {
                for (int i = mBundleList.size() - 1; i >= 0; i--) {
                    if (mBundleList.get(i).id == item.id) {
                        mBundleList.remove(i);
                    }
                }
            }
        }

        if (null != onSelectListener) {
            if (null != mBundleList) {
                onSelectListener.onSelect(mBundleList);
            }
        }


    }


    /**
     * 数据处理
     *
     * @param response
     * @param isRefresh
     */
    private void handleData(List<MarketModel> response, boolean isRefresh) {
        int size = response == null ? 0 : response.size();
        if (size > 0) {
            clear();
            if (null == mBundleList) {
                mBundleList = new ArrayList<>();
            }

            for (MarketModel marketModel : response) {
                if (!modelMap.containsKey(marketModel.id)) {
                    modelMap.put(marketModel.id, marketModel);
                }


            }
            Collection<MarketModel> values = modelMap.values();
            List<MarketModel> assetsModels = new ArrayList<MarketModel>(values);

            //自定义排序1
            Collections.sort(assetsModels, new Comparator<MarketModel>() {
                @Override
                public int compare(MarketModel t1, MarketModel t2) {
                    if (t1.rank > t2.rank) {
                        return 1;
                    } else {
                        return -1;
                    }
                }
            });

            if (isRefresh) {
                setAdapter(mAddMoreAdapter);
                mAddMoreAdapter.setNewData(assetsModels);
            } else {
                mAddMoreAdapter.addData(response);
                mAddMoreAdapter.loadMoreComplete();
            }
        } else {
            mAddMoreAdapter.loadMoreEnd(isRefresh);
        }
    }

    private void clear() {
        if (list.size() > 0) {
            list.clear();
        }

    }

}
